import React, {FC, useState} from 'react';
import styles from "./index.less";
import logo from "@/assets/logo.svg";
import {CopyrightOutlined} from '@ant-design/icons';
import {Button, Checkbox, Col, Form, Input, Row} from "antd";
import {LockTwoTone, SafetyCertificateOutlined, UserOutlined} from "@ant-design/icons/lib";
import {getLoginBackgroundStyle, getPageQuery, setCurrentUser} from "@/utils/utils";
import {history} from 'umi';
import service from "@/pages/sys/login/service";
import {LoginUserModel} from "@/pages/sys/login/data";
import {Helmet, HelmetProvider} from "react-helmet-async";
import config from "@/config";
import {SysUserModel} from "@/pages/sys/user/data";

interface LoginProps {}

// 登录页面背景图片样式
const backgroundStyle = getLoginBackgroundStyle();

//页面标题
const title = "西交投信息系统开发平台 系统登录"

/** 登录组件 */
const Login: FC<LoginProps> = () => {
  const [form] = Form.useForm();
  const [submitBtnText, setSubmitBtnText] = useState('登 录');
  const [submitting, setSubmitting] = useState(false);
  const [autoLogin, setAutoLogin] = useState(false);
  const [requireCaptcha, setRequireCaptcha] = useState(false);
  const [captcha, setCaptcha] = useState();

  const handleLogin = async (values: { [key: string]: any }) => {
    setSubmitting(true);
    const model = values as LoginUserModel;

    //验证码检测
    let cresult = await service.requireCaptcha(model.account);
    //如果当前账号需要验证码并且验证码组件不显示时,先显示验证码组件让用户输入,阻止提交
    if (cresult.success && !requireCaptcha) {
      setSubmitting(false);//设置登录状态
      setCaptcha(await service.captcha(model.account));//刷新验证码
      setRequireCaptcha(true);//显示验证码
      return;
    }

    //登录检测
    let result = await service.login(model);
    //如果登录失败
    if (!result.success) {
      setSubmitting(false);
      //如果失败并且验证码已经存在,则需要刷新验证码
      if (requireCaptcha) {
        setCaptcha(await service.captcha(model.account));//刷新验证码
      }
      return;
    }

    //登录成功,页面跳转
    setSubmitBtnText('登陆成功,正在跳转...');
    //登录成功后设置用户token
    setCurrentUser(result.data as SysUserModel);
    const urlParams = new URL(window.location.href);
    const params = getPageQuery();
    let {redirect} = params as { redirect: string };
    if (redirect) {
      const redirectUrlParams = new URL(redirect);
      if (redirectUrlParams.origin === urlParams.origin) {
        redirect = redirect.substr(urlParams.origin.length);
        if (redirect.match(/^\/.*#/)) {
          redirect = redirect.substr(redirect.indexOf('#') + 1);
        }
      } else {
        window.location.href = '/';
        return;
      }
    }
    history.replace(redirect || '/');
  }

  const handleCaptchaClick = async () => {
    const account = form.getFieldValue('account');
    setCaptcha(await service.captcha(account));
  }

  return (
    <HelmetProvider>
      <Helmet>
        <title>{title}</title>
        <meta name="description" content={title}/>
      </Helmet>

      <div className={styles.container} style={backgroundStyle}>
        <div className={styles.content}>
          <div className={styles.top}>
            <div className={styles.header}>
              <div>
                <img alt="logo" className={styles.logo} src={logo}/>
              </div>
              <span className={styles.title}>西交投业务管理系统</span>
            </div>
          </div>
          <div className={styles.main}>
            <div className={styles.login}>
              <Form form={form} onFinish={handleLogin}>
                <Form.Item name="account" rules={[{required: true, message: '请输入用户名!'}]}>
                  <Input size="large" prefix={<UserOutlined className={styles.prefixIcon}/>} placeholder="请输入用户名"/>
                </Form.Item>
                <Form.Item name="password" rules={[{required: true, message: '请输入密码!'}]}>
                  <Input type="password" size="large" prefix={<LockTwoTone className={styles.prefixIcon}/>} placeholder="请输入密码"/>
                </Form.Item>

                {requireCaptcha && (
                  <Row gutter={8}>
                    <Col span={14}>
                      <Form.Item name="captcha" rules={[{required: true, message: '请输入验证码！'}]}>
                        <Input size="large" prefix={<SafetyCertificateOutlined className={styles.prefixIcon}/>} placeholder="请输入验证码"/>
                      </Form.Item>
                    </Col>
                    <Col span={10}>
                      <img src={captcha} onClick={handleCaptchaClick} alt="点击切换验证码"/>
                    </Col>
                  </Row>
                )}

                <div>
                  <Checkbox className={styles.autoLogin} checked={autoLogin} onChange={e => setAutoLogin(e.target.checked)}>
                    自动登录
                  </Checkbox>
                </div>
                <Form.Item>
                  <Button loading={submitting} className={styles.submit} size="large" htmlType="submit">
                    {submitBtnText}
                  </Button>
                </Form.Item>
              </Form>
            </div>
          </div>
        </div>
        <footer className={styles.footer}>
          <footer className={styles.footerx}>
            <div className={styles.footerLinks}>
              <a target="_blank" href="http://localhost:54321">项目主页</a>
              <a target="_blank" href="http://localhost:54321/doc.html">接口文档</a>
              <a target="_blank" href="https://www.yuque.com/lvyanyang/yikko8/">开发框架</a>
            </div>
            <div className={styles.footerCopyright}>
              Copyright <CopyrightOutlined/> {config.copyright}
            </div>
          </footer>
        </footer>
      </div>
    </HelmetProvider>
  );
}

export default Login;
